package com.example;

import com.example.entity.Data;

import java.util.concurrent.TimeUnit;

/**
 * @Author: wyp
 * @Date: 2021/9/7 14:58
 */
public class VolatileDemo {
    public static void main(String[] args) {
//        visibilityDemo();
//        atomicDemo();
        atomicDemo2();

    }

    /**
     * 原子性Demo
     */
    private static void atomicDemo() {
        Data data = new Data();

        for (int i = 0; i < 20; i++) {
            new Thread(()->{
                for (int j = 0; j < 100; j++) {
                    data.addData();
                }
            },String.valueOf(i)).start();
        }

        //线程大于2，main不执行
        while (Thread.activeCount() > 2){
            Thread.yield();
        }

        System.out.println("计算结果："+data.getData());
    }

    private static void atomicDemo2() {
        Data data = new Data();

        for (int i = 0; i < 20; i++) {
            new Thread(()->{
                for (int j = 0; j < 100; j++) {
                    data.addData();
                    data.addAtomic();
                }
            },String.valueOf(i)).start();
        }

        //线程大于2，main不执行
        while (Thread.activeCount() > 2){
            Thread.yield();
        }

        System.out.println("计算结果："+data.getData());
        System.out.println("atomic计算结果："+data.getAtomicInteger());
    }

    /**
     * 可见性Demo
     */
    private static void visibilityDemo() {
        Data data = new Data();
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " is running !start ");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            data.setData(50);
            System.out.println(Thread.currentThread().getName() + " is running !end " + data.getData());
        }, "A").start();

        while (data.getData() == 0) {
            //不可见导致死循环 TODO 这里不能写输出代码，否则修改能够被主线程感知
        }

        System.out.println(Thread.currentThread().getName() + " is running !end " + data.getData());
    }
}
